﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Emz.Core.Models.Enums;
using Newtonsoft.Json;

namespace Emz.Core.Models
{
    public class TimeRecord
    {
        public int Day { get; set; }
        public DateTime? TimeIn { get; set; }
        public DateTime? TimeOut { get; set; }
        public int Holiday { get; set; }
        private double _requiredWorkingHours;
        
        [JsonIgnore]
        public double RequiredWorkHours 
        {
            get { return _requiredWorkingHours; }
            set { _requiredWorkingHours = value; } 
        }
        public double TotalWorkHours
        {
            get
            {
                if (!TimeIn.HasValue || !TimeOut.HasValue) return 0.0;
                TimeSpan ts = TimeOut.Value - TimeIn.Value;
                return ts.TotalHours > 0.0 ? ts.TotalHours : 0.0;
            }
        }
        [JsonIgnore]
        public double RegularHours
        {
            get
            {
                var expectedRegularHours = TotalWorkHours - OverTime - NightDifference;
                return expectedRegularHours;
            }
        }
        [JsonIgnore]
        public double OverTime
        {
            get
            {
                var expectedOvertime = TotalWorkHours > RequiredWorkHours ? TotalWorkHours - RequiredWorkHours : 0.0;
                return expectedOvertime;
            }
        }
        [JsonIgnore]        
        public double NightDifference
        {
            get
            {
                if (TotalWorkHours <= 0) return 0.0;

                var startNightDiff = new DateTime(TimeIn.Value.Year, TimeIn.Value.Month, TimeIn.Value.Day, 22, 0, 0); //10PM
                var endNightDiff = new DateTime(TimeOut.Value.Year, TimeOut.Value.Month, TimeIn.Value.Day == TimeOut.Value.Day ? TimeOut.Value.AddDays(1).Day : TimeOut.Value.Day, 06, 0, 0); //06AM

                var nighDiff = 0.0;
                var validHours = endNightDiff.Subtract(startNightDiff).TotalHours; //8 hours
                if (TimeOut.Value > startNightDiff)
                {
                    var expectedValue = TimeOut.Value.Subtract(startNightDiff).TotalHours;
                    nighDiff = expectedValue <= validHours ? expectedValue : validHours;
                }

                return Math.Round(nighDiff, 2);
            }
        }       
    }
}
